package com.gcu.common.network

import com.gcu.common.constant.Server
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class RetrofitManager private constructor() {

    private val mRetrofit: Retrofit

    init {
        //创建OkhttpClient
        val builder = OkHttpClient.Builder()
        builder.connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
        builder.readTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS)
        //添加公共参数拦截器
        val commonInterceptor = HttpCommonInterceptor.Companion.Builder().build()
        builder.addInterceptor(commonInterceptor)
        mRetrofit = Retrofit.Builder()
            .client(builder.build())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(Server.BASE_URL)
            .build()
    }

    fun <T> create(service: Class<T>): T {
        return mRetrofit.create(service)
    }

    companion object {
        /**
         * 超时时间
         * Default Time Out
         */
        private const val DEFAULT_TIME_OUT = 5L

        /**
         * 读取时间
         * Default Read Time Out
         */
        private const val DEFAULT_READ_TIME_OUT = 10L

        fun getInstance() = Holder.instance
    }

    private object Holder {
        val instance = RetrofitManager()
    }


}